package cn.chinasyq.photoquan.user.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.chinasyq.photoquan.R;
import cn.chinasyq.photoquan.base.OnFragmentShowListener;
import cn.chinasyq.photoquan.user.activity.AboutActivity;
import cn.chinasyq.photoquan.user.activity.EditUserInfoActivity;
import cn.chinasyq.photoquan.user.activity.FeedbackActivity;
import cn.chinasyq.photoquan.user.activity.LoginActivity;
import cn.chinasyq.photoquan.user.activity.MyAlbumActivity;
import cn.chinasyq.photoquan.user.activity.MyGamesActivity;
import cn.chinasyq.photoquan.user.bean.UserInfo;
import cn.chinasyq.photoquan.user.mode.UserMode;
import cn.chinasyq.photoquan.view.CircleImageView;
import cn.master.util.utils.RequestCodeUtil;
import cn.master.util.utils.ToastUtil;
import cn.master.volley.commons.VolleyHelper;
import cn.master.volley.models.response.handler.ResponseHandler;

public class UserManagementFragment extends Fragment implements
        OnClickListener, ResponseHandler.OnSucceedListener, ResponseHandler.OnFailedListener, OnFragmentShowListener {

    @SuppressWarnings("unused")
    private static final String TAG = UserManagementFragment.class.getName();
    private static final String TAG_GET_INFO = "get_info";

    private View view = null;
    private CircleImageView ivHeadPortrait = null;
    private TextView tvUserName = null;
    private TextView tv_score;
    private LinearLayout llytHeader = null;


//    private SwitchAnimationUtil animatorutil;
    private LinearLayout rlytCollection;
    private TextView tv_game_num, tvCollection = null;
    private UserInfo bean;
    private LinearLayout ly_vip;
    private LinearLayout ly_about;
    private LinearLayout ly_feedback;
    private LinearLayout ly_logout;

    @SuppressLint("InflateParams")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_user_management, null);
        initComponent();
        registerListener();
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }


    /**
     * 初始化组件
     */
    private void initComponent() {
        ivHeadPortrait = (CircleImageView) view.findViewById(R.id.iv_head_portrait);
        ivHeadPortrait.setDefaultImageResId(R.mipmap.bg_head_portrait);
        ivHeadPortrait.setErrorImageResId(R.mipmap.bg_head_portrait);
        tvUserName = (TextView) view.findViewById(R.id.tv_nick_name);
        tv_score = (TextView) view.findViewById(R.id.tv_score);
        tv_score.setOnClickListener(this);
        tvUserName.setOnClickListener(this);
        llytHeader = (LinearLayout) view.findViewById(R.id.llyt_header);
//        animatorutil = new SwitchAnimationUtil();
//        animatorutil.setmDuration(200);
        rlytCollection = (LinearLayout) view
                .findViewById(R.id.ly_collection);
        tvCollection = (TextView) view.findViewById(R.id.tv_collection);
        ly_vip = (LinearLayout) view
                .findViewById(R.id.ly_vip);
        ly_about = (LinearLayout) view
                .findViewById(R.id.ly_about);
        ly_feedback = (LinearLayout) view
                .findViewById(R.id.ly_feedback);
        ly_logout = (LinearLayout) view
                .findViewById(R.id.ly_logout);
        tv_game_num = (TextView) view.findViewById(R.id.tv_game_num);
    }

    /**
     * 注册监听器
     */
    private void registerListener() {
        ivHeadPortrait.setOnClickListener(this);
        llytHeader.setOnClickListener(this);
        rlytCollection.setOnClickListener(this);
        ly_vip.setOnClickListener(this);
        ly_about.setOnClickListener(this);
        ly_feedback.setOnClickListener(this);
        ly_logout.setOnClickListener(this);

    }

    /**
     * 加载数据
     */
    private void loadNativeData() {
        bean = UserMode.getCurrentUserInfo(getActivity());
        tvUserName.setText(bean.getName());
        tv_score.setText("积分："+bean.getScore());
        tv_score.setVisibility(View.VISIBLE);
        tvCollection.setText(String.valueOf(bean.getAlbum_photos_count()));
        tv_game_num.setText(String.valueOf(bean.getGame_photos_count()));
        ivHeadPortrait.setImageUrl(bean.getLogo(), VolleyHelper.getImageLoader());
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iv_head_portrait:
                if (islogin())
                callEditInfo();
                break;
            case R.id.ly_collection:
                if (islogin())
                callCollect();
                break;
            case R.id.ly_vip:
                if (islogin())
                callVPD();
                break;
            case R.id.ly_feedback:
                callFeedBack();
                break;
            case R.id.ly_about:
                callAbout();
                break;
            case R.id.ly_logout:
                if (islogin())
                logout();
                break;
            default:
                if (islogin()){}
                break;
        }

    }

    boolean islogin() {
        if (UserMode.isLogin(getActivity())) {
            return true;
        } else {
            callLogin();
            return false;
        }
    }

    private void callAbout() {
        startActivity(new Intent(getActivity(), AboutActivity.class));
    }

    private void callFeedBack() {
        startActivity(new Intent(getActivity(), FeedbackActivity.class));
    }

    private void callVPD() {
        startActivity(new Intent(getActivity(), MyGamesActivity.class));
    }


    private void callCollect() {
        startActivity(new Intent(getActivity(), MyAlbumActivity.class));
    }

    private void callEditInfo() {
        startActivity(new Intent(getActivity(), EditUserInfoActivity.class));
    }

    private void logout() {
        UserMode.logout(getActivity());
        onShow();
    }

    /**
     * 登陆
     */
    private void callLogin() {
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        getActivity().startActivityForResult(intent, RequestCodeUtil.getInstance().obtainRequestCode(LoginActivity.class));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RequestCodeUtil.getInstance().obtainRequestCode(LoginActivity.class)) {
            if (resultCode == Activity.RESULT_OK) {
                onShow();
            }
        }
    }

    /**
     * 获取我的简介（登陆后）
     */
    private void obtainMyProfile() {
        bean = UserMode.getCurrentUserInfo(getActivity());
        ResponseHandler handler = new ResponseHandler(TAG_GET_INFO);
        handler.setOnSucceedListener(this);
        handler.setOnFailedListener(this);
        UserMode.obtainMyProfile(bean.getToken(), handler);
    }

    /**
     * 获取数据成功后，填充页面
     */
    @Override
    public void onSucceed(String tag, boolean isCache, Object data) {
        ((UserInfo) data).setToken(UserMode.getCurrentUserInfo(getActivity()).getToken());
        UserMode.save(getActivity(), (UserInfo) data);
        loadNativeData();
    }

    @Override
    public void onFailed(String tag, ResponseHandler.FailedStatus status, int resultCode, String msg) {
        if (msg == null) {
            switch (status) {
                case DATA_ERROR:
                    ToastUtil.show(getActivity(), R.string.tip_data_error);
                    break;
                case NETWORK_ERROR:
                    ToastUtil.show(getActivity(), R.string.servererrortips);
                    break;
            }
        } else {
            ToastUtil.show(getActivity(), msg);
        }
        loadNativeData();
    }

    @Override
    public void onShow() {
        if (UserMode.isLogin(getActivity())) {
            ly_logout.setVisibility(View.VISIBLE);
            obtainMyProfile();
        } else {
            ly_logout.setVisibility(View.GONE);
            tv_score.setVisibility(View.GONE);
            tvUserName.setText("点击登录");
            ivHeadPortrait.setImageUrl("", VolleyHelper.getImageLoader());
        }
//        animatorutil.startAnimation(ivHeadPortrait, SwitchAnimationUtil.AnimationType.SCALE);
    }
}
